let editor;
let to;
let type = 1;
const activyClass = "activity";
// 第一，菜单 class ，Button 菜单继承 BtnMenu class

const E = window.wangEditor

class AlertMenu extends E.BtnMenu {
    constructor(editor) {
        // data-title属性表示当鼠标悬停在该按钮上时提示该按钮的功能简述
        const $elem = E.$(`<div class="w-e-menu"><i class="w-e-icon-image"></i></div>`)
        super($elem, editor)
    }

    // 菜单点击事件
    clickHandler() {
        $("#imgFile").click()
    }

    tryChangeActive() {
        // this.active()
    }
}

function uploadImg() {
    var formData = new FormData();
    formData.append('file', document.getElementById('imgFile').files[0]);
    $.ajax({
        url: "http://www.im.com/data/chat/uploadImg",
        type: "post",
        data: formData,
        cache: false,
        contentType: false,
        // 用于对data参数进行序列化处理 这里必须false
        processData: false,
        success: function (data) {
            if (data && "null" != data) {
                editor.cmd.do('insertHTML', '<p><img src="' + data + '"></p>');
            } else {
                alert("上传失败！");
            }
            $("#imgFile").val("");
        },
        error: function (data) {
            alert("上传失败")
        }
    });
}

function initData() {
    $("#usernameSpan").html(user.user);
    $(".chart-list-items ul").html("");
    // TODO 后面改为一起返回
    // 初始化群组和当前用户信息
    $.ajax({
        url: "http://www.im.com/data/chat/groups",
        success: function (result) {
            handResult("g", result);
        }
    });
    $.ajax({
        url: "http://www.im.com/data/chat/users",
        success: function (result) {
            handResult("u", result);
        }
    });
}

function handResult(type, result) {
    var html = [];
    for (let i = 0; i < result.length; i++) {
        if (i > 8) {
            break;
        }
        if (result[i] === user.user) {
            continue;
        }
        html.push('<li id="' + type + "-" + result[i] + '" onclick="switchChat(\'' + type + '\', \'' + result[i] + '\', ' + getType(type) + ')">');
        html.push('<div class="avatar"><img src="image/Avatar-4.png" alt=""></div>');
        html.push('<div class="name">' + (type === "u" ? "用户：" : "群组：") + result[i] + '</div>');
        html.push('<div class="newMsg">●</div>');
        html.push('</li>');
    }
    $(".chart-list-items ul").append(html.join(""));
}

$(document).ready(function () {
    var E = window.wangEditor;
    editor = new E('#messageInput');
    // 菜单 key ，各个菜单不能重复
    const customUploadImgKey = 'customUploadImg';
    editor.menus.extend(customUploadImgKey, AlertMenu);

    editor.config.height = 130;
    // 隐藏插入网络图片的功能
    editor.config.showLinkImg = false;
    // 配置全屏功能按钮是否展示
    editor.config.showFullScreen = false;
    // 配置菜单
    editor.config.menus = [
        'bold',
        'fontSize',
        'fontName',
        'emoticon',
        customUploadImgKey,
    ];
    // 或者 var editor = new E( document.getElementById('editor') )
    editor.create();
});

/**
 * 切换聊天群组和频道
 * @param toId
 * @param msgType
 */
function switchChat(userType, toId, msgType) {
    cleanMsg();
    to = toId;
    type = msgType;
    // 加载历史聊天记录
    editor.txt.clear();
    console.log(getToByType(userType, to));
    // 取消消息小红点
    $("#" + getToByType(userType, to) + " .newMsg").hide();
    $(".chart-list-items ul li").removeClass(activyClass);
    $("#" + getToByType(userType, to)).addClass(activyClass);
    $.ajax({
        url: "http://www.im.com/data/chat/msg?from=" + user.user + "&to=" + to + "&type=" + msgType,
        success: function (result) {
            for (const d in result.data) {
                console.log(result.data.length)
                showMsg(result.data[result.data.length - d - 1]);
            }
            scrollBottom();
        }
    });
}

/**
 * 显示消息
 * @param message
 * @param data
 */
function showMsg(message) {
    let obj = $("#" + getToByType(getTypeStr(message.type), message.to));
    // 找到指定群组，判断是否激活，激活则增加消息内容，未激活则设置有新消息
    if (obj.length == 0) {
        obj = $("#" + getToByType(getTypeStr(message.type), message.from));
        if (obj.length == 0) {
            console.log("对象不存在");
            return;
        }
    }
    if (obj.hasClass(activyClass)) {
        $(".chart-msg-box").append("<div class='time'>时间:" + (message.createTime && 'null' != message.createTime ? message.createTime : new Date().toLocaleString()) + "</div>");
        $(".chart-msg-box").append("<div class='info' >" + message.body + "</div>");
        scrollBottom();
    } else {
        // 设置显示有新消息，根据消息类型来处理单点或群组消息
        $("#" + getToByType(getTypeStr(message.type), message.to) + " .newMsg").show();
    }
}

function getType(type) {
    return type == "u" ? 1 : 2;
}

function getTypeStr(type) {
    return type == 1 ? "u" : "g";
}

function getToByType(type, to) {
    return type + "-" + to;
}

/**
 * 清空消息
 * @param message
 * @param data
 */
function cleanMsg() {
    $(".chart-msg-box").html("");
}

function sendMsg() {
    if (!to) {
        alert("请选择消息接收对象！");
        return;
    }
    var message = editor.txt.html();
    if (!message) {
        return
    }
    fyWebsocket.sendMsg(user.user, to, message, type);
    showMsg(message);
    scrollBottom();
    editor.txt.clear();
}

function initNotification() {
    //判断浏览器是否支持桌面通知
    if (window.Notification) {
        var notification = window.Notification;
        if (notification.permission == "default") {
            notification.requestPermission(function (permission) {
            });
        }
    }
}

function scrollBottom() {
    $("#msgBox").scrollTop = $("#msgBox").scrollHeight;
}

function formatDate(time, format = 'YY-MM-DD hh:mm:ss') {
    const date = new Date(time);

    const year = date.getFullYear(),
        //月份是从0开始的
        month = date.getMonth() + 1,
        day = date.getDate(),
        hour = date.getHours(),
        min = date.getMinutes(),
        sec = date.getSeconds();
    const preArr = Array.apply(null, Array(10)).map(function (elem, index) {
        return '0' + index;
    });

    const newTime = format.replace(/YY/g, year)
        .replace(/MM/g, preArr[month] || month)
        .replace(/DD/g, preArr[day] || day)
        .replace(/hh/g, preArr[hour] || hour)
        .replace(/mm/g, preArr[min] || min)
        .replace(/ss/g, preArr[sec] || sec);
    return newTime;
};
